//
//  SLCAPMController.m
//  Objective-C
//
//  Created by 陆承东 on 2018/7/1.
//  Copyright © 2018年 S_Line. All rights reserved.
//

#import "SLCAPMController.h"

@interface SLCAPMController ()

@property (nonatomic, weak) CALayer *colorLayer;

@end

@implementation SLCAPMController

- (void)initNavBar {
    self.navTitle = @"CAPresentation&Model";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavBar];
    
    [self initView];
}

- (void)initView {
    // create a red layer
    CALayer *colorLayer = [CALayer layer];
    self.colorLayer = colorLayer;
    self.colorLayer.frame = CGRectMake(100, 100, 100, 100);
    self.colorLayer.position = CGPointMake(self.view.bounds.size.width / 2.0, self.view.bounds.size.height / 2.0);
    self.colorLayer.backgroundColor = [UIColor redColor].CGColor;
    [self.view.layer addSublayer:self.colorLayer];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // get the touch point
    CGPoint point = [[touches anyObject] locationInView:self.view];
    if ([self.colorLayer.presentationLayer hitTest:point]) {
        // randomize the layer background color
        CGFloat red = arc4random() / (CGFloat)INT_MAX;
        CGFloat green = arc4random() / (CGFloat)INT_MAX;
        CGFloat blue = arc4random() / (CGFloat)INT_MAX;
        self.colorLayer.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0].CGColor;
    } else {
        // ohterwise (slowly) move the layer to new position
        [CATransaction begin];
        [CATransaction setAnimationDuration:1.0];
        self.colorLayer.position = point;
        [CATransaction commit];
    }
}

@end
